<script>
  export default {
    name: 'h5_recursive_list',
    data() {
      return {
        data: [],
      };
    },
    props: {
      children: {
        type: Array,
        default: () => {
          return [];
        },
      },
      dynamicPage: {
        type: Number,
        default: 1,
      },
    },
    watch: {
      children(newValue, oldValue) {
        //this.init()
        this.data = newValue;
      },
    },
  };
</script>
<script module="genealogyRender" lang="renderjs">
      import sheep from '@/sheep';
      export default{
        data(){
          return {
            // 每一层的虚拟DOM
            virtualDom:null
          }
        },
        watch:{
          children(newValue,oldValue) {
            this.init()
          },
        },
        computed:{
          nc_image(){
            return sheep.$store('AI').nc_image
          }
        },
        methods: {
          init() {
            // 生成最外边的虚拟Dom
            let htmlText = this.createElement(
              'div',
              {class:`flex`}
            )
            const minShi = Math.min(...this.children.map(item => item.shi));
            const maxShi = Math.max(...this.children.map(item => item.shi));
            // 将数组进行分割并筛选出最长的数组
            const shiMap = new Map();
            for(let i = minShi; i <= maxShi; i++){
              shiMap.set(i, this.children.filter(item => item.shi === i));
            }
            const reassembledMap = new Map();
            for (const [key, values] of shiMap) {
              const newValues = [];
              const usedIndices = new Set();
              for (let i = 0; i < values.length; i++) {
                if (usedIndices.has(i)) continue;
                const value = values[i];
                const spouseVal = [];
                // 遍历 spouses 数组
                for (const spouseId of value.spouses) {
                  for (let j = 0; j < values.length; j++) {
                    if (usedIndices.has(j)) continue;
                    const otherValue = values[j];
                    if (otherValue.id === spouseId) {
                        spouseVal.push(otherValue);
                        usedIndices.add(j);
                    }
                  }
                }
                const newObj = {
                  ...value,
                  spouse_val: spouseVal
                };
                newValues.push(newObj);
                usedIndices.add(i);
              }
              reassembledMap.set(key, newValues);
            }
            // 循环遍历 Map
            // 从最后一层开始循环处理
            let currentLevelKey = [...reassembledMap.keys()].pop();

            let nameMap =[];
            // 记录每一层生成的dom
            let successDom = []
            const minKey = Math.min(...reassembledMap.keys());

            while (currentLevelKey >= minKey) {
              if(!reassembledMap.get(currentLevelKey)){
                currentLevelKey--
                return
              }
              // 获取当前层的数据
              const currentLevelData = reassembledMap.get(currentLevelKey);

              // 用于分组的对象
              const groupedData = {};

              // 遍历当前层数据进行分组
              currentLevelData.forEach(item => {
                const key = `${item.fq_id}-${item.mq_id}`;
                if (!groupedData[item.id]) {
                  groupedData[item.id] = [];
                }

                groupedData[item.id].push(this.createElement('div',{class:`person flex align-center justify-center  ${item.sex == 1 ? 'bg_6FA0FC':'bg_FC6F6F'}`},[],{},`${item.surname}${item.name}`,item));

                // 处理 spouse_val 长度大于 1 的情况
                if (item.spouse_val.length > 0) {
                  item.spouse_val.forEach(spouse => {
                    groupedData[item.id].push(this.createElement('div',{class:`person flex align-center justify-center  ${spouse.sex == 1 ? 'bg_6FA0FC':'bg_FC6F6F'}`},[],{},`${spouse.surname}${spouse.name}`,spouse));
                  });
                }
              });

              console.log('+++++++++++++++++++++++++++');
              const mergeData = this.mergeData(successDom,groupedData)
              console.log(mergeData);



              successDom = groupedData
              console.log(currentLevelKey,'============================');
              if(currentLevelKey == 4){
                return
              }
              // const layer = this.createElement('div',{class:'flex'})
              // 将分组结果转换为数组
              // 将 JSON 数据转换为数组
              // let result = [];
              // for (let key in groupedData) {
              //   console.log(successDom);
              //   result = result.concat(groupedData[key]);
              // }
              // layer.children = result
              // successDom = layer.children

              // 移动到上一层
              currentLevelKey--;
            }

            // htmlText.children.push(successDom)
            // console.log('生成的text=》',htmlText);

            // 创建虚拟DOM
            // const allDom = document.getElementById('genealogy_tree')
            // this.render(htmlText,allDom)
          },
          // 定义 createElement 函数
          createElement(tag, props = {}, children = [], incident = {},text='',item = {}) {
            return {
              tag,
              props,
              children,
              incident,
              text,
              item
            };
          },
          // 将虚拟 DOM 转换为真实 DOM 节点的函数
          render(vnode, container) {
              const el = document.createElement(vnode.tag);
              // 设置属性
              for (const [key, value] of Object.entries(vnode.props)) {
                  el.setAttribute(key, value);
              }
              // 添加事件
              for (const [key, value] of Object.entries(vnode.incident)) {
              console.log(key, value)
                  el.addEventListener(key, value);
              }
              // 处理子节点
              for (const child of vnode.children) {
                  if (typeof child === 'string') {
                      el.appendChild(document.createTextNode(child));
                  } else {
                     this.render(child, el);
                  }
              }
              // 添加文本信息
              if(!!vnode.text){
                el.innerHTML = vnode.text
              }
              container.appendChild(el);
          },
          mergeData(data1, data2) {
console.log(data1,data2);

            // 创建一个 id 到对应对象的映射
      const idMap = {};
      for (const key in data2) {
          data2[key].forEach(item => {
              idMap[item.item.id] = item;
          });
      }

      for (const key in data1) {
          const arr1 = data1[key];

          for (const item of arr1) {
              let target;
              // 先尝试用 mq_id 匹配

              if (item.item.mq_id && idMap[item.item.mq_id] && data2.length > 2) {
                  target = idMap[item.item.mq_id];
              } else if (item.item.fq_id && idMap[item.item.fq_id]) {
                  // 再尝试用 fq_id 匹配
                  target = idMap[item.item.fq_id];
              }
              if (target) {
                  target.children.push(item);
              }
          }
      }
      
      return data2;
          }
        }
      }
</script>

<template>
  <view id="genealogy_tree" :children="data"></view>
</template>

<style lang="scss" scoped></style>
